﻿using AutoMapper;
using B.S.GridManager.Api.Read.Application.Command.Department;
using B.S.GridManager.Api.Read.Dtos;
using B.S.GridManager.ErrorCode;
using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using MediatR;
using System.Collections.Generic;

namespace B.S.GridManager.Api.Read.Application.CommandHandler.Department
{
    /// <summary>
    /// 查询部门树处理类
    /// </summary>
    public class GetDepartmentHandler : IRequestHandler<GetDepartmentCommand, ApiResult<List<DepartmentTreeDTO>>>
    {
        private readonly IBaseRepository<DepartmentModel> departRepo;
        private readonly IMapper mapper;

        //注入部门仓储
        public GetDepartmentHandler(IBaseRepository<DepartmentModel> departRepo,IMapper mapper)
        {
            this.departRepo = departRepo;
            this.mapper = mapper;
        }

        /// <summary>
        /// 查询部门树处理方法
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>所有部门数据列表</returns>
        public Task<ApiResult<List<DepartmentTreeDTO>>> Handle(GetDepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DepartmentTreeDTO>> result = new ApiResult<List<DepartmentTreeDTO>>();//实例化响应包装类
            result.Data = GetTree(0);//查询父id=0的所有下级部门

            result.Code = ApiEnums.Success;
            result.Msg = "递归查找所有部门数据成功!";
            return Task.FromResult(result); 
        }
        /// <summary>
        /// 递归查找所有下级部门
        /// </summary>
        /// <param name="parentId">下级部门的父id</param>
        /// <returns></returns>
        private List<DepartmentTreeDTO> GetTree(long parentId)
        {
            var departs = departRepo.GetAll().Where(x => x.ParentId == parentId);//查询所有parentId父id=传过来的id
                var departDtos = mapper.Map<List<DepartmentTreeDTO>>(departs);//把查询表达式转换为DTO列表
            foreach (var dto in departDtos) {
                dto.Children = GetTree(dto.Id);
            }
            return departDtos;
        }
    }
}
